js获取dom元素宽高的方法

您所在的位置:网站首页 获取元素高度 js js获取dom元素宽高的方法

js获取dom元素宽高的方法

2024-06-09 03:25| 来源: 网络整理| 查看: 265

① dom.style.width / height

这种⽅法,有⼀定局限性,只能取内联样式的宽⾼。

var d = document.getElementById('id').style.height console.log(d) ② dom.currentStyle.width / height

这种⽅法,也是有⼀定局限性,不过我们三种常⽤css样式都能获取。但是只⽀持 IE ,其它浏览器不⽀持

③ window.getComputedStyle(dom).width / height var d = document.getElementById('id') console.log( window.getComputedStyle(d).height)

⽀持所有浏览器,兼容性好

④ dom.getBoundingClientRect().width / height

这种⽅法,⼀般⽤于计算元素的绝对位置,根据视窗左上⻆的点来算的。可以拿到四个元素 值: left 、 top 、 width 、 height

#id{ height: 100px; width: 100px; margin-left: 20px; margin-top: 20px; } // 只支持内联样式 // var d = document.getElementById('id').style.height // console.log(d) //都支持,兼容性好 // var d = document.getElementById('id') // console.log( window.getComputedStyle(d).height) var d = document.getElementById('id') console.log(d.getBoundingClientRect())

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3